package com.zhuozhou.jdyc.api;

import com.zhuozhou.jdyc.base.BaseException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by fz on 2020/9/9 14:11
 * describe:请求失败，重试机制，当请求过期时利用Function方法重新请求刷新token方法替换请求token，然后再重新请求
 * 设置3次重试，每次间隔1秒,但仅适用于用户登录过期刷新token和无权限刷新用户菜单时使用
 */
public class RetryWithDelay implements Function<Observable<? extends Throwable>, Observable<?>> {
    /**
     * 最大出错重试次数
     */
    private int maxRetries = 3;
    /**
     * 当前出错重试次数
     */
    private int retryCount = 0;
    protected ApiServiceHelper apiServiceHelper = ApiRetrofit.getInstance().getApiService();

    public RetryWithDelay() {
    }

    /**
     *
     * @param maxRetries 最大重试次数
     */
    public RetryWithDelay(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    @Override
    public Observable<?> apply(Observable<? extends Throwable> observable) throws Exception {
        return observable
                .flatMap((Function<Throwable, ObservableSource<?>>) throwable -> {

                    if (throwable instanceof BaseException) {
                        BaseException baseException = (BaseException) throwable;
                        if (++retryCount <= maxRetries && UserAccountHelper.isLoginPast(baseException.getErrorCode())) {
                            // 如果上面检测到token过期就会进入到这里
                            // 然后下面的方法就是更新token
                            UserAccountHelper.saveLoginPast(false);
//                            return apiServiceHelper.login(new RequestLoginBean(UserAccountHelper.getAccount(),
//                                    UserAccountHelper.getPassword(), 1))
//                                    .subscribeOn(Schedulers.io())
//                                    .observeOn(AndroidSchedulers.mainThread())
//                                    .unsubscribeOn(Schedulers.io())
//                                    .doOnNext(loginResultBean -> {
//                                        UserAccountHelper.saveLoginPast(true);
//                                        UserAccountHelper.setToken(loginResultBean.getToken());
//                                        UserAccountHelper.setRefreshToken(loginResultBean.getRefreshToken());
//                                    });// 这里更新完成后就会进行重订阅，从Observable.just(null)重新开始走。
                        } else if (++retryCount <= maxRetries && UserAccountHelper.isNoPermission(baseException.getErrorCode())) {
                            return apiServiceHelper.getAppUserMenu()
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .unsubscribeOn(Schedulers.io())
                                    .doOnNext(list ->{
//                                        UserAccountHelper::saveAppMenu
                                    });
                        }
                    }
                    return Observable.error(throwable);
                });
    }

}
